import { defineStore } from "pinia";
import { accountLogin,getUserInfo,getUserRole } from "@/services/login";
import { IAccount } from "@/services/login/type";
import localCache from '@/utils/cache'
import { routesMapToMenu } from "@/utils/routeToMenu";
import router from "@/router";
const useLoginStore = defineStore('login', {
  state: () => ({
    token: localCache.getCache('token')||'',
    name: localCache.getCache('name')||'',
    id: localCache.getCache('id')||'',
    userInfo: localCache.getCache('userInfo')||{},
    roleList:localCache.getCache('roleList')||[]
  }),
  getters: {
    
  },
  actions: {
    async accountlLogin(account: IAccount) {
      const res = await accountLogin(account)
      if (res) {
        const { token,id,name } = res.data
        this.token = token
        localCache.setCache('token', token)
        this.id = id 
        localCache.setCache('id', id)
        this.name = name
        localCache.setCache('name', name)
        const info = await getUserInfo(id)
        this.userInfo = info.data
        localCache.setCache('userInfo', info.data)
        const roles = await getUserRole(info.data.role.id)
        this.roleList = roles.data
        localCache.setCache('roleList', roles.data)
        
        //动态添加路由
        this.addRoutes()
        
        router.push('/main')
      }
    },
    addRoutes() {
      const routes = routesMapToMenu(this.roleList)  
      routes.forEach(route => {
        router.addRoute('main',route)
      })
    }
  }
})
export default useLoginStore